//
//  RHDeviceDistributeVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/8/11.
//

#import "RHDeviceDistributeVC.h"
#import "RHDeviceDistributeCell.h"
#import "RHDeviceModel.h"
#import "RHUserModel.h"
#import "RHSearchView.h"

@interface RHDeviceDistributeVC ()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableArray *deviceArr;

@property(nonatomic,strong)NSMutableArray *DeviceSelectArr;

@property(nonatomic,strong)QMUIButton *distributeBtn;


@property (nonatomic, strong) UISearchController *searchController;

@property (nonatomic ,strong) RHSearchView *searchView;



@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;
//总数
@property (nonatomic, assign) NSInteger totalCount;
@end

@implementation RHDeviceDistributeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设备分发".rh_localized;
    self.view.backgroundColor = CFTabViewBgColor;
    
    self.currentPage = 1;
    self.numOfPage = 10;
    self.requestType = RequestTypeRefresh;
    [self setupUI];
    [self getNoDistribleDeviceList];
}
#pragma mark ---- 获取未分发的设备 -----
-(void)getNoDistribleDeviceList
{
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"pageNum":@(self.currentPage),
                           @"pageSize":@(self.numOfPage),
                           @"deviceId":self.searchView.searchTextField.text
    };
    [RHDeviceModel startGetWithCompletionAPIKey:H_getNoBindList argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        

        self.totalCount = [request.responseObject[@"total"] integerValue];
        self.totalPage = self.totalCount%self.numOfPage? self.totalCount/self.numOfPage+1 : self.totalCount/self.numOfPage;
        NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
        //下拉刷新
        if(self.requestType == RequestTypeRefresh){
            [self.DeviceSelectArr removeAllObjects];
            [self.tableView endHeaderRefresh];
            self.deviceArr = arr;
        }else{//上拉加载
            [self.tableView endFooterRefresh];
            [self.deviceArr addObjectsFromArray:arr];
        }
        if(self.currentPage >= self.totalPage){
            [self.tableView endFooterRefreshCustomWithNoMoreData];
        }
        [self.tableView reloadData];
       
        if(self.deviceArr.count == 0){
            [self.tableView endFooterRefreshWithNoMoreData];
        }
        [self.distributeBtn setTitle:[NSString stringWithFormat:@"%@(%ld/%ld)",@"分发".rh_localized,self.DeviceSelectArr.count,self.totalCount] forState:UIControlStateNormal];
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        [self.tableView endFooterRefresh];
        
    }];
    
}


- (void)setupUI{
    kWeakSelf;
    _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
    _searchView.delegate = self;
    _searchView.searchTextField.placeholder = @"请输入设备ID".rh_localized;
    [self.view addSubview:_searchView];
   
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHDeviceDistributeCell class] forCellReuseIdentifier:@"RHDeviceDistributeCell"];
    [self.view addSubview:_tableView];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        //_resultTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
        //_resultTableView.sectionHeaderTopPadding = 0;
    }
    
    _distributeBtn = [[QMUIButton alloc]init];
    [_distributeBtn setTitle:@"Distribute" forState:UIControlStateNormal];
    [_distributeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_distributeBtn setBackgroundColor:CMainColorGreen];
    _distributeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:19];
    _distributeBtn.layer.cornerRadius = 8;
    _distributeBtn.layer.masksToBounds = YES;
    [self.view addSubview:_distributeBtn];
    [_distributeBtn addTarget:self action:@selector(distributeDeviceToUser) forControlEvents:UIControlEventTouchUpInside];
    [_distributeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.bottom.mas_offset(-kSafe_bottom-20);
        make.height.offset(kScaleW(45));
    }];
    

    [_tableView addHeaderRefresh:^{
        [weakSelf.tableView.mj_footer resetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
        [weakSelf getNoDistribleDeviceList];
        
    }];
    
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getNoDistribleDeviceList];
    }];
    
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(weakSelf.searchView.mas_bottom);
        make.bottom.equalTo(weakSelf.distributeBtn.mas_top).offset(-10);
    }];
    
}



#pragma mark ----- 分发设备给下级用户 (终端以上级别用户)---
-(void)distributeDeviceToUser
{
    if(self.DeviceSelectArr.count == 0){
        [QMUITips showInfo:@"请选择一个设备".rh_localized];
        return;
    }
    NSMutableArray *deviceIDs = [NSMutableArray array];
    for (RHDeviceModel *device in self.DeviceSelectArr) {
        [deviceIDs addObject:@(device.device_id)];
    }
    NSDictionary *para = @{@"userId":@(self.userId),
                           @"id":deviceIDs
    };
    kWeakSelf;
    [QMUITips showLoading:@"设备分发中...".rh_localized inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_devicesBind argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            
            [QMUITips showSucceed:@"分发成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter]postNotificationName:DeviceListNeedUpdateNotification object:nil];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}


#pragma mark ------ tableView delegate --------

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.deviceArr.count;
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHDeviceModel *deviceModel = self.deviceArr[indexPath.row];
    RHDeviceDistributeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHDeviceDistributeCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.deviceModel = deviceModel;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    RHDeviceModel *model = self.deviceArr[indexPath.row];
    
    
    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeSmallInstaller && self.DeviceSelectArr.count>=1&&!model.isSelected){
        [QMUITips showError:@"安装工人一次只能分发一个设备".rh_localized];
        return;
    }
    
    model.isSelected = !model.isSelected;
    if(model.isSelected){
        [self.DeviceSelectArr addObject:model];
    }else{
        [self.DeviceSelectArr removeObject:model];
    }
    
    [self.tableView reloadData];
   
    
    [self.distributeBtn setTitle:[NSString stringWithFormat:@"%@(%zd/%zd)",@"分发".rh_localized,self.DeviceSelectArr.count,self.totalCount] forState:UIControlStateNormal];
    
}

#pragma mark - textfield delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    [self getNoDistribleDeviceList];
    [self.searchView.searchTextField resignFirstResponder];
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getNoDistribleDeviceList];
        [self.searchView.searchTextField resignFirstResponder];
    });
    return YES;
}


#pragma mark ----- lazy
-(NSMutableArray *)deviceArr
{
    if(!_deviceArr){
        _deviceArr = [NSMutableArray array];
    }
    return _deviceArr;
}

-(NSMutableArray *)DeviceSelectArr
{
    if(!_DeviceSelectArr){
        _DeviceSelectArr = [NSMutableArray array];
    }
    return _DeviceSelectArr;
}

@end
